from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile
from .sers import UserSer
from django.http.response import HttpResponse,FileResponse
from .utils import CodeUtils
from captcha.image import ImageCaptcha
from io import BytesIO
import redis

r=redis.Redis(host='localhost',port=6379)


class UniqueUserView(APIView):
    def post(self,request):

        # 1、获取传递来的用户名
        username=request.data.get('username')
        # 2、从数据库查询
        queryset=UserProfile.objects.filter(username=username)
        # 3、验证
        if queryset:
            return Response({'msg':'用户名已存在','code':400})
        # 4、返回
        else:
            return Response({'msg':'用户名可用','code':200})


# 注册接口
class RegisterView(APIView):
    def post(self,request):
        # 获取传递过来的图片验证码
        img_code=request.data.get('img_code')
        # 获取传递来的key
        key=request.GET.get('key')
        # 从redis中取出保存的数据
        code=r.get(key)
        if not code:
            return Response({'msg':'图片验证码过期','code':400})
        if code.decode()!=img_code:
            return Response({'msg':'图片验证码不正确','code':400})
        # 1、创建一个序列化类
        ser=UserSer(data=request.data)
        # 2、数据验证
        if ser.is_valid():
            # 保存到数据库
            ser.save()
            return Response({'msg':'注册成功','code':200})
        else:
            return Response({'msg':'注册失败','error':ser.errors,'code':400})

# 验证码生成接口
def make_img_code(request):
    # 1、先生成一个验证码
    code=CodeUtils.make_code_n(4)
    key=request.GET.get('key')
    r.set(key,code,60)
    # 2、生成一张图片对象
    image_captcha=ImageCaptcha()
    image=image_captcha.generate_image(code)
    # 3、创建一个字节流
    bytes_io=BytesIO()
    # 4、把对象存入字节流对象
    image.save(bytes_io,'jpeg')
    # 5、返回
    return HttpResponse(bytes_io.getvalue(),content_type='image/jpeg')